package xyz.ifanfan.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;

import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class CharacterFilter implements Filter {

    //敏感词汇集合
    private List<String> list = new ArrayList<String>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext context = filterConfig.getServletContext();
        String realPath = context.getRealPath("/WEB-INF/敏感词汇.txt");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), StandardCharsets.UTF_8));
            String line = null;
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            for (String s : list) {
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //request
        ServletRequest request_proxy = (ServletRequest) Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(),
                servletRequest.getClass().getInterfaces(), new RequestProxy(servletRequest, list));

        //response
        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(request_proxy, servletResponse);
    }
}
